package com.bdqn.dao.impl;

import com.bdqn.dao.BaseDao;
import com.bdqn.dao.BookDao;
import com.bdqn.entity.Book;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * BookDaoImpl 图书DAO实现类
 *
 * @author LILIBO
 * @since 2024/4/27
 */
public class BookDaoImpl extends BaseDao implements BookDao {

    private static final Logger log = LogManager.getLogger(BaseDao.class);

    /**
     * 添加图书
     *
     * @param book
     * @return
     */
    @Override
    public int add(Book book) {
        String sql = "insert book values(default,?,?,?,?,?,?)";
        Object[] params = {book.getbName(), book.getAuthor(), book.getPubComp(), book.getPubDate(), book.getbCount(), book.getPrice()};
        return super.execute(sql, params);
    }

    /**
     * 修改图书
     *
     * @param book
     * @return
     */
    @Override
    public int upd(Book book) {
        String sql = "update book set pubDate=? where bid=?";
        Object[] params = {book.getPubDate(), book.getBid()};
        return super.execute(sql, params);
    }

    /**
     * 删除图书
     *
     * @param bid
     * @return
     */
    @Override
    public int del(int bid) {
        String sql = "delete from book where bid=?";
        Object[] params = {bid};
        return super.execute(sql, params);
    }

    /**
     * 查询列表
     *
     * @return
     */
    @Override
    public List<Book> list() {
        // 返回列表
        List<Book> list = new ArrayList<>();

        // 定义SQL语句
        String sql = "select * from book";

        // 获取数据库连接
        Connection conn = super.getConnection();
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            // 创建数据库操作对象
            pstmt = conn.prepareStatement(sql);
            // 执行数据查询
            rs = pstmt.executeQuery();
            // 处理查询结果
            while (rs.next()) {
                // 获取列数据
                int bid = rs.getInt("bid");
                String bName = rs.getString("bName");
                String author = rs.getString("author");
                String pubComp = rs.getString("pubComp");
                String pubDate = rs.getString("pubDate");
                int bCount = rs.getInt("bCount");
                float price = rs.getFloat("price");
                // 创建对象并添加到集合
                list.add(new Book(bid, bName, author, pubComp, pubDate, bCount, price));
            }
        } catch (SQLException e) {
            log.error(e.fillInStackTrace());
        } finally {
            // 关闭连接释放资源
            super.closeAll(rs, pstmt, conn);
        }
        // 返回查询结果
        return list;
    }

}
